﻿using AutoMapper;
using MediatR;
using Newtonsoft.Json;
using PublicClass.HttpClient;
using S.Produce.Api.Application.Commands.BreedingCommands;
using S.Produce.Domains;
using S.Produce.Domains.DTO;
using S.Produce.Infrastructure;

namespace S.Produce.Api.Application.CommandHandlers.BreedingCommandHandlers
{
    /// <summary>
    /// 添加配种信息Handler
    /// </summary>
    public class BreedingCreateCommandHandler : IRequestHandler<BreedingCreateCommand, int>
    {
        private readonly IRepository<Breeding> _repository;
        private readonly IMapper mapper;
        private readonly ServiceHttpClient _serviceHttpClient;

        /// <summary>
        /// 构造方式注入
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="mapper"></param>
        /// <param name="serviceHttpClient"></param>
        public BreedingCreateCommandHandler(IRepository<Breeding> repository, IMapper mapper, ServiceHttpClient serviceHttpClient)
        {
            _repository = repository;
            this.mapper = mapper;
            _serviceHttpClient = serviceHttpClient;
        }

        /// <summary>
        /// 添加配种信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<int> Handle(BreedingCreateCommand request, CancellationToken cancellationToken)
        {
            var count = 0;
            var info = new Breeding();
            request.CreateDate = DateTime.Now.Date;
            request.UpdateDate = null;
            request.UpdateBy = null;
            count += await _repository.CreateAsync(mapper.Map<BreedingCreateCommand, Breeding>(request, info));

            //添加种母配种信息之后需要把羊只档案种的妊娠状态改完已妊娠
            //根据耳号找到羊只档案信息
            //var sheepInfo = await _serviceHttpClient.Get("http://10.31.56.15:8090/api/SheepFile/SheepFileConditionFinds?card=" + request.Earbugles);
            //通过反序列化来将妊娠状态改完已妊娠
            //var sheepDetail = JsonConvert.DeserializeObject<SheepDetailDto>(sheepInfo);
            //sheepDetail.PregnancyTest = true;
            //await _serviceHttpClient.Post("http://10.31.56.15:8080/api/SheepFile/SheepFileConditionUpdate", sheepDetail);

            return count;
        }
    }
}
